package com.lagou.zk;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZkUtils {
    static Logger logger = LoggerFactory.getLogger(ZkUtils.class);


    //  获取连接
    public static ZkClient getCon(){
        ZkClient zkClient = new ZkClient(Const.ZKHOSTS);
        logger.info("get Connection!");
        return zkClient;
    }

    /**
     * 创建节点和数据
     * @param zkClient zk客户端
     * @param path zk节点路径
     */
    public static void createNode(ZkClient zkClient, String path){
//       判断节点是否存在
        boolean exists = zkClient.exists(path);
        String dbConfig = Const.JDBCURL +"\t" + Const.USERNAME + "\t" + Const.PASSWORD;
        logger.info("dbConfig is " +dbConfig);
//        不存在则创建
        if (!exists){
//        创建节点并写入数据库连接信息
            zkClient.createPersistent(path,true);
            zkClient.writeData(path,dbConfig);
            System.out.println("create success!");
//            zkClient.delete(path);
        }else {
            zkClient.writeData(path,dbConfig);
            System.out.println("new dbconfig is " + dbConfig);
            System.out.println("data write success!!!");
        }
        System.out.println(path +" created!");
    }
}
